

/**
 * 非微信小程序只有 开发版 和 正式版
 * develop  开发版
 * trial	  体验版
 * release	正式版
 */
export type EnvVersion = 'develop' | 'trial' | 'release';
type EnvTYLE =
  | 'ICON_URL'
  | 'BASE_URL'
  | 'H5_BASE_URL'
  | 'CLOUD_SCHOOL'
  | 'REQUEST_FILE_SERVER'
  | 'CDN_IMG_HEAD'
  | 'CDN_IMG_COMPRESSRATE'
  | 'SUBSCRIBEMSG_TEMPIDS';

export function useEnv() {
  /** 商协互联 商协帮pro 商协盟 */
  const TEST_MINIPROGRAM = ['wx3efcbfd36920b0ab', 'wx9381f12dbdd32652', 'wx500e59ad7ae269c9'];
  const env = import.meta.env;

  const envObj: { [x: string]: string } = {};

  let miniProgram: UniApp.MiniProgram;
  let envVersion: EnvVersion;

  // #ifndef MP-WEIXIN
  envVersion = env.MODE === 'development' ? 'develop' : 'release';
  // #endif

  // #ifdef MP-WEIXIN
  miniProgram = uni.getAccountInfoSync().miniProgram;
  envVersion = miniProgram?.envVersion;
  // #endif

  Object.keys(env).forEach((key) => {
    let item: any[] = key.split('_');
    if (item[0] === 'UNIAPP') {
      item.splice(0, 1);
      const envVer = item[0].toLocaleLowerCase() as string
      if (['develop', 'trial', 'release'].includes(envVer)) {
        if (envVer === envVersion) {
          item.splice(0, 1);
          // #ifdef MP
          // 强制测试小程序中, 体验版连接测试服务器
          if (key.includes(`${envVer.toLocaleUpperCase()}_BASE_URL`)) {

            const appid = miniProgram.appId;
            envObj[item.join('_') as string] =
              TEST_MINIPROGRAM.includes(appid)
                ? env[`UNIAPP_DEVELOP_BASE_URL`]
                : (env[key] as string);

          } else {
            envObj[item.join('_') as string] = env[key] as string;
          }
          // #endif
          // #ifndef MP
          envObj[item.join('_') as string] = env[key] as string;
          // #endif
        }
      } else {
        envObj[item.join('_') as string] = env[key] as string;
      }
    }
  });

  /**
   * 获取环境变量数据
   * @param type
   * @returns
   */
  function getEnv(type: EnvTYLE) {
    return envObj[type]
  }

  /**
   * 应用是否运行在生产环境
   * @returns boolean
   */
  function isProdMode() {
    return env.PROD;
  }

  /**
   * 应用是否运行在开发环境
   * @returns boolean
   */
  function isDevMode() {
    return env.DEV;
  }

  /** 当前是否是测试环境 (指定小程序) */
  function isTestEnv() {
    return envVersion !== 'release' && TEST_MINIPROGRAM.includes(miniProgram.appId);
  }

  return {
    envVersion,
    getEnv,
    isProdMode,
    isDevMode,
    isTestEnv,
  };
}
